var express = require('express');
var router = express.Router();
var {sequelize, User} = require('../moudles/accessdb/dao/userlogin')
const {success, fail, error, loginsucess, loginfail} = require('../common/resultcode')
const {handleRequest, addUser} = require('../service/users/userregister')
const {handleLogin, handleValidUser} = require("../service/users/loginservice");

/* to login  前缀路径 /users */
router.post('/login', async function (req, res, next) {
    let user = handleLogin(req.body).then((userinfo) => {
        handleValidUser(userinfo)
            //u是数据库查询到的值
            .then((u) => {
                //验证用户是否存在
                if (u) {
                    //登录成功
                    console.log(' 登录成功' + u.userName);
                    loginsucess.id=u.userId;
                    res.json(loginsucess)
                }
                //查询结构为null
                else {
                    //用户名或密码错误
                    res.status(401).json(loginfail)
                }

            })
            .catch((e) => {

            })

    })
        .catch((e) => {
            //非法用户信息
            res.json(e)
        })
    // res.send('respond with user: ' + res.json(user));
    // res.json(user);
});

//注册路由
router.post('/register', async function (req, res) {
    // res.json(fail);
    handleRequest(req.body).then((userinfo) => {
        // console.log('info:::::'+userinfo)
        addUser(userinfo, res);

    }).catch((e) => {
        // console.log('errllll:'+e)
        //非法用户信息
        res.json(e)
    });

})

module.exports = router;
